package clientClasses;

import commonClasses.Messages.LastItemMsg;
import commonClasses.commonInterfaces.ProtocolIntf;
import commonClasses.Messages.ItemMsg;
import commonClasses.Messages.ListMsg;
import commonClasses.MagicNumbers;
import commonClasses.Messages.Msg;
import commonClasses.Utils;
import commonClasses.commonInterfaces.ClientModelIntf;
import commonClasses.commonInterfaces.ItemIntf;
import java.util.ArrayList;

public class GetItemsOrder {

    private ProtocolIntf _clientProtocol = null;
    private ClientModelIntf _model = null;

    public GetItemsOrder(ProtocolIntf cp) {
        _clientProtocol = cp;
        _model = _clientProtocol.getClientModel();
    }

    public void go() {
        ArrayList<ItemIntf> itemList = new ArrayList<ItemIntf>();
        ListMsg listMsg = new ListMsg(_clientProtocol);
        try {

            Utils.write("wysyłam..");
            listMsg.send();
            Utils.write("jestem tu");
            long receivedMsgID = Msg.receiveMsgId(_clientProtocol.getDIS());
            Utils.write("jestem tu2");
            boolean stop = false;
            while (!stop) {
                if (receivedMsgID == MagicNumbers.ITEM_MSG_NR) {
                    ItemMsg itemMsg = new ItemMsg(_clientProtocol, null);
                    itemMsg.receive();
                    itemList.add(itemMsg.getItem());
                    receivedMsgID = Msg.receiveMsgId(
                            _clientProtocol.getDIS());
                    itemMsg.getItem().lookInside();
                } else if (receivedMsgID == MagicNumbers.LAST_ITEM_MSG_NR) {
                    stop = true;
                    LastItemMsg lastItemMsg =
                            new LastItemMsg(_clientProtocol);
                    lastItemMsg.receive();
                    itemList.add(lastItemMsg.getItem());
                    lastItemMsg.getItem().lookInside();
                }
            }

            if(_model!=null) {
            _model.updateSerwerItems(_clientProtocol.getIP(),
                    _clientProtocol.getPort(), itemList);
            } else {
                Utils.write("model == null");
            }
        } catch (Exception e) {
            e.printStackTrace();
            Utils.write("mam wyjątek!");
        }
    }
}
